#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Image
import os.path
import sys
from itertools import izip, count
import glob

def get_color_table(in_im):
    im = in_im.copy()
    lut = im.resize((256,1))
    lut.putdata(range(256))
    lut = lut.convert("RGB").getdata()
    return list(lut)



def get_invert_color(color_table, color_index):
    invert_rgb = [ 256-ci for ci in color_table[color_index] ]
    f = lambda t: sum([ abs(v1-v2) for v1,v2 in izip(invert_rgb, t)])
    min, ic = f(color_table[0]), 0 #first element
    for v, i in izip(color_table, count()):
        space  = f(v)
        if space == 0:
            return  i
        if space < min: 
            min, ic = space, i 
    return ic


def create_invert_image(in_fn, out_fn):
    im = Image.open(in_fn)
    assert im.mode == 'P'
    color_table = get_color_table(im)
    #print color_table
    data=[]
    trans_color = im.info['transparency']
    #print trans_color
    for i in im.getdata():
        if i != trans_color:
            data.append( get_invert_color(color_table, i) )
        else:
            data.append(i)
    im.putdata(data)
    im.save(out_fn, transparency=trans_color)


def main():
    in_fns = glob.glob('../media/card_[0-9]*.gif')
    #print in_fns, len(in_fns)
    for fn in in_fns:
        print fn
        base, ext = os.path.splitext(fn)
        fn_invert = base+'_hl'+ext
        print fn_invert
        create_invert_image(fn, fn_invert)


if __name__ == '__main__':
    main()
